package org.zky.modules.customer.service.impl;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.zky.exception.EntityExistException;
import org.zky.modules.customer.domain.ZkyUserTab;
import org.zky.modules.customer.repository.ZkyUserTabRepository;
import org.zky.modules.customer.service.ZkyUserTabService;
import org.zky.modules.customer.service.dto.ZkyUserTabDto;
import org.zky.modules.customer.service.dto.ZkyUserTabQueryCriteria;
import org.zky.modules.customer.service.mapper.ZkyUserTabMapper;
import org.zky.utils.FileUtil;
import org.zky.utils.PageUtil;
import org.zky.utils.QueryHelp;
import org.zky.utils.ValidationUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
* @author chenglong
* @date 2020-03-23
*/
@Service
//@CacheConfig(cacheNames = "zkyUserTab")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ZkyUserTabServiceImpl implements ZkyUserTabService {

    private final ZkyUserTabRepository zkyUserTabRepository;

    private final ZkyUserTabMapper zkyUserTabMapper;

    public ZkyUserTabServiceImpl(ZkyUserTabRepository zkyUserTabRepository, ZkyUserTabMapper zkyUserTabMapper) {
        this.zkyUserTabRepository = zkyUserTabRepository;
        this.zkyUserTabMapper = zkyUserTabMapper;
    }

    @Override
    //@Cacheable
    public Map<String,Object> queryAll(ZkyUserTabQueryCriteria criteria, Pageable pageable){
        Page<ZkyUserTab> page = zkyUserTabRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(zkyUserTabMapper::toDto));
    }

    @Override
    //@Cacheable
    public List<ZkyUserTabDto> queryAll(ZkyUserTabQueryCriteria criteria){
        return zkyUserTabMapper.toDto(zkyUserTabRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public ZkyUserTabDto findById(Long userId) {
        ZkyUserTab zkyUserTab = zkyUserTabRepository.findById(userId).orElseGet(ZkyUserTab::new);
        ValidationUtil.isNull(zkyUserTab.getUserId(),"ZkyUserTab","userId",userId);
        return zkyUserTabMapper.toDto(zkyUserTab);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public ZkyUserTabDto create(ZkyUserTab resources) {
        if(zkyUserTabRepository.findByUserName(resources.getUserName()) != null){
            throw new EntityExistException(ZkyUserTab.class,"user_name",resources.getUserName());
        }
        if(zkyUserTabRepository.findByMobileNo(resources.getMobileNo()) != null){
            throw new EntityExistException(ZkyUserTab.class,"mobile_no",resources.getMobileNo());
        }
        return zkyUserTabMapper.toDto(zkyUserTabRepository.save(resources));
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(ZkyUserTab resources) {
        ZkyUserTab zkyUserTab = zkyUserTabRepository.findById(resources.getUserId()).orElseGet(ZkyUserTab::new);
        ValidationUtil.isNull( zkyUserTab.getUserId(),"ZkyUserTab","id",resources.getUserId());
        ZkyUserTab zkyUserTab1 = null;
        zkyUserTab1 = zkyUserTabRepository.findByUserName(resources.getUserName());
        if(zkyUserTab1 != null && !zkyUserTab1.getUserId().equals(zkyUserTab.getUserId())){
            throw new EntityExistException(ZkyUserTab.class,"user_name",resources.getUserName());
        }
        zkyUserTab1 = zkyUserTabRepository.findByMobileNo(resources.getMobileNo());
        if(zkyUserTab1 != null && !zkyUserTab1.getUserId().equals(zkyUserTab.getUserId())){
            throw new EntityExistException(ZkyUserTab.class,"mobile_no",resources.getMobileNo());
        }
        zkyUserTab.copy(resources);
        zkyUserTabRepository.save(zkyUserTab);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Long[] ids) {
        for (Long userId : ids) {
            zkyUserTabRepository.deleteById(userId);
        }
    }

    @Override
    public void download(List<ZkyUserTabDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZkyUserTabDto zkyUserTab : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" userName",  zkyUserTab.getUserName());
            map.put("user mobile", zkyUserTab.getMobileNo());
            map.put("1:PC 2:wechat", zkyUserTab.getSource());
            map.put("1:active 2:inactive", zkyUserTab.getStatus());
            map.put("delete time", zkyUserTab.getDeleteAt());
            map.put(" createTime",  zkyUserTab.getCreateTime());
            map.put(" updateTime",  zkyUserTab.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}